<?php
/**
 * Created by PhpStorm.
 * User: huynguyen
 * Date: 10/8/14
 * Time: 8:15 PM
 */

namespace Backend\Modules\User\Controllers;
use Backend\Modules\User\Forms\FormLogin;

class LoginController extends \Phalcon\Mvc\Controller
{
    public function initialize()
    {
        $this->view->setTemplateAfter('login');
    }

    public function indexAction()
    {
        if($this->auth->isUserSignedIn())
        {
            return $this->response->redirect($this->getDi()->get('config')->application->backendRedirectUri);
        }

        $form = new FormLogin();

        try {
            if (!$this->request->isPost())
            {

            } else {
                if ($form->isValid($this->request->getPost()) == false) {
                    foreach ($form->getMessages() as $message) {
                        $this->flash->error($message);
                    }
                } else {
                    $this->auth->check(array(
                        'email' => $this->request->getPost('email'),
                        'password' => $this->request->getPost('password'),
                        'remember' => $this->request->getPost('remember')
                    ));
                    return $this->response->redirect($this->getDi()->get('config')->application->backendRedirectUri . '/user');
                }
            }
        } catch (\Exception $e) {
            $this->flash->error($e->getMessage());
        }

        $this->view->form = $form;
    }
} 